import React from 'react';
import { Form, message, Card, Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import userInfo from '@/utils/userInfo';
import { login } from './service/api';
import './Login.scss';

interface LoginForm {
  username: string;
  password: string;
}

const Index: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const from = (location.state as { from?: Location })?.from?.pathname || '/dashboard';
  const [form] = Form.useForm();

  const onFinish = async (values: LoginForm) => {
    try {
      const res = await login(values.username, values.password);
      const { code, data: datas } = res;
      if (code === 0 && datas?.length) {
        const data = datas[0];
        userInfo.loginSuccess(data.id, data.userName, data.userPwd);
        navigate(from, { replace: true });
        message.success('登录成功');
      } else {
        message.error('用户名或密码错误');
      }
    } catch {
      message.error('登录失败');
    }
  };

  return (
    <div className="login-container">
      <Card className="login-card">
        <div className="login-title">
          <h1>后台管理系统</h1>
          <p>Welcome Back</p>
        </div>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              className="login-input"
              prefix={<UserOutlined style={{ color: '#1a237e' }} />}
              placeholder="用户名：admin"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              className="login-password"
              prefix={<LockOutlined style={{ color: '#1a237e' }} />}
              placeholder="密码：admin123"
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              block
              className="login-button"
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Index; 